#include "menumanager.h"
#include <QTimer>
#include <QRegularExpression>
#include <QDebug>
#include <algorithm>

namespace RestaurantSystem {

// 静态成员初始化
MenuManager* MenuManager::s_instance = nullptr;
const int MenuManager::DEFAULT_STOCK_THRESHOLD = 5;

MenuManager::MenuManager(QObject* parent)
    : QObject(parent)
    , m_dataManager(nullptr)
    , m_stockCheckTimer(new QTimer(this))
    , m_isInitialized(false)
    , m_dataLoaded(false)
{
    // 设置库存检查定时器(每30分钟检查一次)
    m_stockCheckTimer->setInterval(30 * 60 * 1000);
    connect(m_stockCheckTimer, &QTimer::timeout, this, &MenuManager::onStockCheckTimer);
}

MenuManager::~MenuManager()
{
    if (m_stockCheckTimer) {
        m_stockCheckTimer->stop();
    }
}

MenuManager& MenuManager::instance()
{
    if (!s_instance) {
        s_instance = new MenuManager();
    }
    return *s_instance;
}

bool MenuManager::initialize()
{
    if (m_isInitialized) {
        return true;
    }
    
    try {
        m_dataManager = &DataManager::instance();
        
        // 加载菜单数据
        if (!loadMenuData()) {
            ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                "Failed to load menu data", 
                "MenuManager::initialize");
            return false;
        }
        
        // 连接DataManager的外部文件变更信号
        connect(m_dataManager, &DataManager::externalFileChanged,
                this, &MenuManager::onExternalFileChanged);
        
        m_isInitialized = true;
        m_stockCheckTimer->start();
        

        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::CRITICAL, 
            QString("MenuManager initialization failed: %1").arg(e.what()), 
            "MenuManager::initialize");
        return false;
    }
}

// ========================================================================
// 菜品管理
// ========================================================================

QList<MenuItem> MenuManager::getAllMenuItems()
{
    QMutexLocker locker(&m_mutex);
    return m_menuItems;
}

MenuItem MenuManager::getMenuItemById(const QString& id)
{
    QMutexLocker locker(&m_mutex);
    
    auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
        [&id](const MenuItem& item) { return item.id == id; });
    
    return (it != m_menuItems.end()) ? *it : MenuItem();
}

QList<MenuItem> MenuManager::getMenuItemsByCategory(const QString& category)
{
    QMutexLocker locker(&m_mutex);
    
    QList<MenuItem> result;
    for (const MenuItem& item : m_menuItems) {
        if (item.category == category) {
            result.append(item);
        }
    }
    return result;
}

QList<MenuItem> MenuManager::searchMenuItems(const MenuSearchCriteria& criteria)
{
    QMutexLocker locker(&m_mutex);
    
    QList<MenuItem> result;
    for (const MenuItem& item : m_menuItems) {
        if (matchesSearchCriteria(item, criteria)) {
            result.append(item);
        }
    }
    return result;
}

MenuOperationResult MenuManager::addMenuItem(const MenuItem& item)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    // 验证数据
    ValidationResult validation = validateMenuItem(item);
    if (!validation.isValid) {
        ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
            QString("Invalid menu item data: %1").arg(validation.errorMessage), 
            "MenuManager::addMenuItem");
        return MenuOperationResult::INVALID_DATA;
    }
    
    // 检查名称重复
    if (isMenuItemNameDuplicate(item.name)) {
        return MenuOperationResult::DUPLICATE_NAME;
    }
    
    try {
        MenuItem newItem = item;
        if (newItem.id.isEmpty()) {
            newItem.id = generateMenuItemId();
        }
        newItem.createdDate = QDateTime::currentDateTime();
        newItem.lastModified = QDateTime::currentDateTime();
        
        // 保存到数据库
        if (m_dataManager->addMenuItem(newItem)) {
            QMutexLocker locker(&m_mutex);
            m_menuItems.append(newItem);
            updateCategoriesList();
            
            // 在发射信号前释放锁，避免死锁
            locker.unlock();
            
            emit menuItemAdded(newItem);
            
            return MenuOperationResult::SUCCESS;
        } else {
            return MenuOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during menu item addition: %1").arg(e.what()), 
            "MenuManager::addMenuItem");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

MenuOperationResult MenuManager::updateMenuItem(const MenuItem& item)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    // 验证数据
    ValidationResult validation = validateMenuItem(item);
    if (!validation.isValid) {
        return MenuOperationResult::INVALID_DATA;
    }
    
    // 检查菜品是否存在
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
        [&item](const MenuItem& existing) { return existing.id == item.id; });
    
    if (it == m_menuItems.end()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    // 检查名称重复(排除自身) - 使用内部版本避免死锁
    if (isMenuItemNameDuplicateInternal(item.name, item.id)) {
        return MenuOperationResult::DUPLICATE_NAME;
    }
    
    try {
        MenuItem updatedItem = item;
        updatedItem.lastModified = QDateTime::currentDateTime();
        int oldStock = it->stock;
        
        // 保存到数据库
        if (m_dataManager->updateMenuItem(updatedItem)) {
            *it = updatedItem;
            updateCategoriesList();
            
            // 在发射信号前释放锁，避免死锁
            locker.unlock();
            
            emit menuItemUpdated(updatedItem);
            
            // 如果库存发生变化，发送库存更新信号
            if (oldStock != updatedItem.stock) {
                emit stockUpdated(updatedItem.id, oldStock, updatedItem.stock);
            }
            
            return MenuOperationResult::SUCCESS;
        } else {
            return MenuOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during menu item update: %1").arg(e.what()), 
            "MenuManager::updateMenuItem");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

MenuOperationResult MenuManager::deleteMenuItem(const QString& id)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
        [&id](const MenuItem& item) { return item.id == id; });
    
    if (it == m_menuItems.end()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    try {
        // 从数据库删除
        if (m_dataManager->deleteMenuItem(id)) {
            QString itemName = it->name;
            m_menuItems.erase(it);
            updateCategoriesList();
            
            // 在发射信号前释放锁，避免死锁
            locker.unlock();
            
            emit menuItemDeleted(id);
            
            return MenuOperationResult::SUCCESS;
        } else {
            return MenuOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during menu item deletion: %1").arg(e.what()), 
            "MenuManager::deleteMenuItem");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

MenuOperationResult MenuManager::batchUpdateMenuItems(const QList<MenuItem>& items)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    try {
        QMutexLocker locker(&m_mutex);
        
        // 验证所有项目
        for (const MenuItem& item : items) {
            ValidationResult validation = validateMenuItem(item);
            if (!validation.isValid) {
                return MenuOperationResult::INVALID_DATA;
            }
        }
        
        // 批量更新
        QList<MenuItem> updatedItems; // 收集更新成功的项目
        for (const MenuItem& item : items) {
            auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
                [&item](const MenuItem& existing) { return existing.id == item.id; });
            
            if (it != m_menuItems.end()) {
                MenuItem updatedItem = item;
                updatedItem.lastModified = QDateTime::currentDateTime();
                
                if (m_dataManager->updateMenuItem(updatedItem)) {
                    *it = updatedItem;
                    updatedItems.append(updatedItem);
                }
            }
        }
        
        updateCategoriesList();
        
        // 在发射信号前释放锁，避免死锁
        locker.unlock();
        
        // 发射更新信号
        for (const MenuItem& item : updatedItems) {
            emit menuItemUpdated(item);
        }
        
        return MenuOperationResult::SUCCESS;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during batch update: %1").arg(e.what()), 
            "MenuManager::batchUpdateMenuItems");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

MenuOperationResult MenuManager::duplicateMenuItem(const QString& sourceId, const QString& newName)
{
    MenuItem sourceItem = getMenuItemById(sourceId);
    if (!sourceItem.isValid()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    // 创建副本
    MenuItem newItem = sourceItem;
    newItem.id = generateMenuItemId();
    newItem.name = newName;
    newItem.salesCount = 0; // 重置销量
    newItem.createdDate = QDateTime::currentDateTime();
    newItem.lastModified = QDateTime::currentDateTime();
    
    return addMenuItem(newItem);
}

// ========================================================================
// 库存管理
// ========================================================================

MenuOperationResult MenuManager::updateStock(const QString& id, int newStock)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
        [&id](const MenuItem& item) { return item.id == id; });
    
    if (it == m_menuItems.end()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    if (newStock < 0) {
        return MenuOperationResult::INVALID_DATA;
    }
    
    try {
        int oldStock = it->stock;
        it->stock = newStock;
        it->lastModified = QDateTime::currentDateTime();
        
        // 保存到数据库
        if (m_dataManager->updateMenuItem(*it)) {
            // 在发射信号前释放锁，避免死锁
            locker.unlock();
            
            emit stockUpdated(id, oldStock, newStock);
            
            return MenuOperationResult::SUCCESS;
        } else {
            it->stock = oldStock; // 回滚
            return MenuOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during stock update: %1").arg(e.what()), 
            "MenuManager::updateStock");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

MenuOperationResult MenuManager::increaseStock(const QString& id, int quantity)
{
    MenuItem item = getMenuItemById(id);
    if (!item.isValid()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    return updateStock(id, item.stock + quantity);
}

MenuOperationResult MenuManager::decreaseStock(const QString& id, int quantity)
{
    MenuItem item = getMenuItemById(id);
    if (!item.isValid()) {
        return MenuOperationResult::ITEM_NOT_FOUND;
    }
    
    if (item.stock < quantity) {
        emit stockInsufficient(id, item.stock, quantity);
        return MenuOperationResult::INSUFFICIENT_STOCK;
    }
    
    return updateStock(id, item.stock - quantity);
}

bool MenuManager::isStockSufficient(const QString& id, int requiredQuantity)
{
    MenuItem item = getMenuItemById(id);
    return item.isValid() && item.stock >= requiredQuantity;
}

QList<StockAlert> MenuManager::getLowStockItems(int threshold)
{
    QMutexLocker locker(&m_mutex);
    
    QList<StockAlert> alerts;
    for (const MenuItem& item : m_menuItems) {
        int itemThreshold = m_stockThresholds.value(item.id, threshold);
        if (item.stock <= itemThreshold) {
            alerts.append(StockAlert(item.id, item.name, item.stock, itemThreshold));
        }
    }
    
    return alerts;
}

bool MenuManager::setStockThreshold(const QString& id, int threshold)
{
    if (threshold < 0) {
        return false;
    }
    
    QMutexLocker locker(&m_mutex);
    m_stockThresholds[id] = threshold;
    return true;
}

MenuOperationResult MenuManager::batchReplenishStock(const QHash<QString, int>& stockUpdates)
{
    if (!m_isInitialized) {
        return MenuOperationResult::SYSTEM_ERROR;
    }
    
    try {
        QMutexLocker locker(&m_mutex);
        
        for (auto it = stockUpdates.begin(); it != stockUpdates.end(); ++it) {
            const QString& itemId = it.key();
            int addQuantity = it.value();
            
            auto itemIt = std::find_if(m_menuItems.begin(), m_menuItems.end(),
                [&itemId](const MenuItem& item) { return item.id == itemId; });
            
            if (itemIt != m_menuItems.end() && addQuantity > 0) {
                int oldStock = itemIt->stock;
                itemIt->stock += addQuantity;
                itemIt->lastModified = QDateTime::currentDateTime();
                
                if (m_dataManager->updateMenuItem(*itemIt)) {
                    emit stockUpdated(itemId, oldStock, itemIt->stock);
                }
            }
        }
        
        return MenuOperationResult::SUCCESS;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during batch stock replenishment: %1").arg(e.what()), 
            "MenuManager::batchReplenishStock");
        return MenuOperationResult::SYSTEM_ERROR;
    }
}

// ========================================================================
// 分类管理
// ========================================================================

QStringList MenuManager::getAllCategories()
{
    QMutexLocker locker(&m_mutex);
    return m_categories;
}

bool MenuManager::addCategory(const QString& category)
{
    if (category.isEmpty()) {
        return false;
    }
    
    QMutexLocker locker(&m_mutex);
    if (!m_categories.contains(category)) {
        m_categories.append(category);
        m_categories.sort();
        QStringList categoriesCopy = m_categories; // 创建副本
        
        // 保存数据到持久化存储
        bool saveSuccess = saveMenuDataInternal();
        if (!saveSuccess) {
            qDebug() << "MenuManager::addCategory - Failed to save menu data";
            // 即使保存失败，也继续执行，因为内存中的数据已经更新
        }
        
        // 在发射信号前释放锁，避免死锁
        locker.unlock();
        
        qDebug() << "MenuManager::addCategory - Emitting categoriesChanged signal with:" << categoriesCopy;
        emit categoriesChanged(categoriesCopy);
        return true;
    }
    return false;
}

bool MenuManager::removeCategory(const QString& category)
{
    if (category.isEmpty()) {
        return false;
    }
    
    // 检查分类是否为空
    if (!isCategoryEmpty(category)) {
        ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
            QString("Cannot remove category '%1': it contains menu items").arg(category), 
            "MenuManager::removeCategory");
        return false;
    }
    
    QMutexLocker locker(&m_mutex);
    bool removed = m_categories.removeOne(category);
    if (removed) {
        QStringList categoriesCopy = m_categories; // 创建副本
        
        // 保存数据到持久化存储
        bool saveSuccess = saveMenuDataInternal();
        if (!saveSuccess) {
            qDebug() << "MenuManager::removeCategory - Failed to save menu data";
            // 即使保存失败，也继续执行，因为内存中的数据已经更新
        }
        
        // 在发射信号前释放锁，避免死锁
        locker.unlock();
        
        emit categoriesChanged(categoriesCopy);
    }
    return removed;
}

bool MenuManager::renameCategory(const QString& oldName, const QString& newName)
{
    if (oldName.isEmpty() || newName.isEmpty() || oldName == newName) {
        return false;
    }
    
    QMutexLocker locker(&m_mutex);
    
    // 更新所有使用该分类的菜品
    bool hasChanges = false;
    for (MenuItem& item : m_menuItems) {
        if (item.category == oldName) {
            item.category = newName;
            item.lastModified = QDateTime::currentDateTime();
            m_dataManager->updateMenuItem(item);
            hasChanges = true;
        }
    }
    
    if (hasChanges) {
        // 更新分类列表
        int index = m_categories.indexOf(oldName);
        if (index >= 0) {
            m_categories[index] = newName;
            m_categories.sort();
        }
        
        // 保存数据到持久化存储
        bool saveSuccess = saveMenuDataInternal();
        if (!saveSuccess) {
            qDebug() << "MenuManager::renameCategory - Failed to save menu data";
            // 即使保存失败，也继续执行，因为内存中的数据已经更新
        }
        
        QStringList categoriesCopy = m_categories; // 创建副本
        
        // 在发射信号前释放锁，避免死锁
        locker.unlock();
        
        emit categoriesChanged(categoriesCopy);
    }
    
    return hasChanges;
}

int MenuManager::getCategoryItemCount(const QString& category)
{
    QMutexLocker locker(&m_mutex);
    
    int count = 0;
    for (const MenuItem& item : m_menuItems) {
        if (item.category == category) {
            count++;
        }
    }
    return count;
}

bool MenuManager::isCategoryEmpty(const QString& category)
{
    return getCategoryItemCount(category) == 0;
}

// ========================================================================
// 销量和统计
// ========================================================================

bool MenuManager::updateSalesCount(const QString& id, int quantity)
{
    if (quantity <= 0) {
        return false;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_menuItems.begin(), m_menuItems.end(),
        [&id](const MenuItem& item) { return item.id == id; });
    
    if (it != m_menuItems.end()) {
        it->salesCount += quantity;
        it->lastModified = QDateTime::currentDateTime();
        int newSalesCount = it->salesCount;
        
        bool success = m_dataManager->updateMenuItem(*it);
        if (success) {
            // 在发射信号前释放锁，避免死锁
            locker.unlock();
            
            // 发射销量更新信号
            emit salesCountUpdated(id, newSalesCount);
        }
        return success;
    }
    
    return false;
}

QList<MenuItem> MenuManager::getPopularItems(int limit)
{
    QMutexLocker locker(&m_mutex);
    
    QList<MenuItem> items = m_menuItems;
    
    // 按销量排序
    std::sort(items.begin(), items.end(), 
        [](const MenuItem& a, const MenuItem& b) {
            return a.salesCount > b.salesCount;
        });
    
    if (limit > 0 && items.size() > limit) {
        items = items.mid(0, limit);
    }
    
    return items;
}

QHash<QString, int> MenuManager::getCategorySales()
{
    QMutexLocker locker(&m_mutex);
    
    QHash<QString, int> categorySales;
    for (const MenuItem& item : m_menuItems) {
        categorySales[item.category] += item.salesCount;
    }
    
    return categorySales;
}

bool MenuManager::resetAllSalesCount()
{
    QMutexLocker locker(&m_mutex);
    
    try {
        for (MenuItem& item : m_menuItems) {
            item.salesCount = 0;
            item.lastModified = QDateTime::currentDateTime();
            m_dataManager->updateMenuItem(item);
        }
        
        ErrorHandler::instance().handleError(ErrorLevel::INFO, 
            "All sales counts have been reset", 
            "MenuManager::resetAllSalesCount");
        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during sales count reset: %1").arg(e.what()), 
            "MenuManager::resetAllSalesCount");
        return false;
    }
}

// ========================================================================
// 数据验证和辅助
// ========================================================================

ValidationResult MenuManager::validateMenuItem(const MenuItem& item)
{
    if (item.name.isEmpty()) {
        return ValidationResult(false, "菜品名称不能为空");
    }
    
    if (item.name.length() > 50) {
        return ValidationResult(false, "菜品名称不能超过50个字符");
    }
    
    if (item.category.isEmpty()) {
        return ValidationResult(false, "菜品分类不能为空");
    }
    
    if (item.price < 0) {
        return ValidationResult(false, "菜品价格不能为负数");
    }
    
    if (item.price > 9999.99) {
        return ValidationResult(false, "菜品价格不能超过9999.99");
    }
    
    if (item.stock < 0) {
        return ValidationResult(false, "库存数量不能为负数");
    }
    
    if (item.stock > 99999) {
        return ValidationResult(false, "库存数量不能超过99999");
    }
    
    return ValidationResult(true);
}

bool MenuManager::isMenuItemNameDuplicate(const QString& name, const QString& excludeId)
{
    QMutexLocker locker(&m_mutex);
    return isMenuItemNameDuplicateInternal(name, excludeId);
}

bool MenuManager::isMenuItemNameDuplicateInternal(const QString& name, const QString& excludeId)
{
    // 内部版本，不获取锁，假设调用者已经获取了锁
    for (const MenuItem& item : m_menuItems) {
        if (item.name == name && item.id != excludeId) {
            return true;
        }
    }
    return false;
}

QString MenuManager::generateMenuItemId()
{
    return "menu_" + QUuid::createUuid().toString().remove('{').remove('}').remove('-');
}

QString MenuManager::generateSmartMenuItemId(const QList<MenuItem> &existingItems)
{
    // 分析现有ID，寻找数字格式ID的最大值
    QList<int> numericIds;
    QStringList uuidIds;
    
    for (const MenuItem &item : existingItems) {
        QString id = item.id;
        
        // 检查是否为纯数字ID
        bool isNumber = false;
        int numericId = id.toInt(&isNumber);
        if (isNumber && id.length() >= 4) { // 假设ID至少4位数
            numericIds.append(numericId);
        } else {
            uuidIds.append(id);
        }
    }
    
    // 如果存在数字ID，继续使用数字ID格式
    if (!numericIds.isEmpty()) {
        // 找到最大的数字ID
        int maxId = *std::max_element(numericIds.begin(), numericIds.end());
        
        // 生成下一个ID
        int nextId = maxId + 1;
        
        // 确保ID不重复
        QString candidateId = QString::number(nextId);
        while (isIdExists(candidateId, existingItems)) {
            nextId++;
            candidateId = QString::number(nextId);
        }
        
        return candidateId;
    }
    
    // 如果没有数字ID，但有UUID格式ID，继续使用UUID格式
    if (!uuidIds.isEmpty()) {
        QString newId;
        do {
            newId = generateMenuItemId();
        } while (isIdExists(newId, existingItems));
        return newId;
    }
    
    // 如果没有任何现有ID，从1001开始
    return "1001";
}

bool MenuManager::isIdExists(const QString &id, const QList<MenuItem> &existingItems)
{
    for (const MenuItem &item : existingItems) {
        if (item.id == id) {
            return true;
        }
    }
    return false;
}

QString MenuManager::getOperationResultMessage(MenuOperationResult result)
{
    switch (result) {
    case MenuOperationResult::SUCCESS:
        return "操作成功";
    case MenuOperationResult::ITEM_NOT_FOUND:
        return "菜品不存在";
    case MenuOperationResult::INVALID_DATA:
        return "数据无效";
    case MenuOperationResult::DUPLICATE_NAME:
        return "菜品名称重复";
    case MenuOperationResult::INSUFFICIENT_STOCK:
        return "库存不足";
    case MenuOperationResult::CATEGORY_NOT_FOUND:
        return "分类不存在";
    case MenuOperationResult::SYSTEM_ERROR:
        return "系统错误";
    default:
        return "未知错误";
    }
}

QString MenuManager::formatPrice(double price)
{
    return QString("¥%1").arg(price, 0, 'f', 2);
}

// ========================================================================
// 公共槽函数
// ========================================================================

void MenuManager::refreshMenuData()
{
    if (loadMenuData()) {

    }
}

void MenuManager::checkStockAlerts()
{
    QList<StockAlert> alerts = getLowStockItems();
    if (!alerts.isEmpty()) {
        emit lowStockAlert(alerts);
    }
}

// ========================================================================
// 私有槽函数
// ========================================================================

void MenuManager::onStockCheckTimer()
{
    checkStockAlerts();
}

void MenuManager::onExternalFileChanged(DataType dataType, const QString& /*filePath*/)
{
    // 当检测到外部文件变更时，如果是菜单数据变更，重新加载缓存
    if (dataType == DataType::MENU) {

        
        // 保存当前库存和销量状态用于比较
        QHash<QString, int> oldStocks;
        QHash<QString, int> oldSalesCounts;
        for (const MenuItem& item : m_menuItems) {
            oldStocks[item.id] = item.stock;
            oldSalesCounts[item.id] = item.salesCount;
        }
        
        // 保存当前菜品信息用于比较
        QHash<QString, MenuItem> oldMenuItems;
        for (const MenuItem& item : m_menuItems) {
            oldMenuItems[item.id] = item;
        }
        
        // 延迟重新加载，确保文件写入完成
        QTimer::singleShot(100, this, [this, oldStocks, oldSalesCounts, oldMenuItems]() {
            if (loadMenuData()) {
                // 检查库存变化并发射信号
                checkAndEmitStockChanges(oldStocks);
                
                // 检查销量变化并发射信号
                checkAndEmitSalesChanges(oldSalesCounts);
                
                // 检查菜品信息变化并发射信号
                checkAndEmitMenuItemChanges(oldMenuItems);
                
                // 发射分类变更信号
                emit categoriesChanged(m_categories);
            }
        });
    }
}

// ========================================================================
// 私有方法
// ========================================================================

bool MenuManager::loadMenuData()
{
    try {
        QMutexLocker locker(&m_mutex);
        
        // 加载菜品数据
        m_menuItems = m_dataManager->getAllMenuItems();
        
        // 直接从DataManager加载分类数据，而不是从菜品中提取
        m_categories = m_dataManager->getMenuCategories();
        
        // 如果分类为空，则使用从菜品中提取的分类作为后备
        if (m_categories.isEmpty()) {
            updateCategoriesList();
        }
        
        m_dataLoaded = true;
        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Failed to load menu data: %1").arg(e.what()), 
            "MenuManager::loadMenuData");
        return false;
    }
}

bool MenuManager::saveMenuData()
{
    try {
        QMutexLocker locker(&m_mutex);
        return saveMenuDataInternal();
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Failed to save menu data: %1").arg(e.what()), 
            "MenuManager::saveMenuData");
        return false;
    }
}

bool MenuManager::saveMenuDataInternal()
{
    // 假设调用者已持有锁，不再获取锁
    try {
        // 保存所有菜品数据
        for (const MenuItem& item : m_menuItems) {
            m_dataManager->updateMenuItem(item);
        }
        
        // 保存分类数据
        bool categoriesUpdated = m_dataManager->updateMenuCategories(m_categories);
        if (!categoriesUpdated) {
            qDebug() << "MenuManager::saveMenuDataInternal - Failed to update categories";
        }
        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Failed to save menu data: %1").arg(e.what()), 
            "MenuManager::saveMenuDataInternal");
        return false;
    }
}

void MenuManager::updateCategoriesList()
{
    // 从现有菜品中提取分类
    QStringList categoriesFromItems;
    for (const MenuItem& item : m_menuItems) {
        if (!categoriesFromItems.contains(item.category)) {
            categoriesFromItems.append(item.category);
        }
    }
    
    // 创建更新后的分类列表
    QStringList updatedCategories = m_categories; // 保留现有的所有分类
    
    // 添加从菜品中发现的新分类
    for (const QString& category : categoriesFromItems) {
        if (!updatedCategories.contains(category)) {
            updatedCategories.append(category);
        }
    }
    
    updatedCategories.sort();
    
    // 只有在分类列表真的发生变化时才更新并发射信号
    if (updatedCategories != m_categories) {
        m_categories = updatedCategories;
        emit categoriesChanged(m_categories);
    }
}

bool MenuManager::matchesSearchCriteria(const MenuItem& item, const MenuSearchCriteria& criteria)
{
    // 关键词搜索
    if (!criteria.keyword.isEmpty()) {
        QString keyword = criteria.keyword.toLower();
        if (!item.name.toLower().contains(keyword) && 
            !item.description.toLower().contains(keyword)) {
            return false;
        }
    }
    
    // 分类过滤
    if (!criteria.category.isEmpty() && item.category != criteria.category) {
        return false;
    }
    
    // 价格范围
    if (criteria.minPrice >= 0 && item.price < criteria.minPrice) {
        return false;
    }
    
    if (criteria.maxPrice >= 0 && item.price > criteria.maxPrice) {
        return false;
    }
    
    // 仅显示有库存的
    if (criteria.inStockOnly && item.stock <= 0) {
        return false;
    }
    
    return true;
}

void MenuManager::emitStockAlertsIfNeeded()
{
    QList<StockAlert> alerts = getLowStockItems();
    if (!alerts.isEmpty()) {
        emit lowStockAlert(alerts);
    }
}

void MenuManager::checkAndEmitStockChanges(const QHash<QString, int>& oldStocks)
{
    // 检查库存变化并发射相应信号
    for (const MenuItem& item : m_menuItems) {
        int oldStock = oldStocks.value(item.id, -1);
        if (oldStock != -1 && oldStock != item.stock) {
            emit stockUpdated(item.id, oldStock, item.stock);
        }
    }
    
    // 检查是否有新增的菜品
    for (const MenuItem& item : m_menuItems) {
        if (!oldStocks.contains(item.id)) {
            emit stockUpdated(item.id, 0, item.stock);
        }
    }
}

void MenuManager::checkAndEmitSalesChanges(const QHash<QString, int>& oldSalesCounts)
{
    // 检查销量变化并发射相应信号
    for (const MenuItem& item : m_menuItems) {
        int oldSalesCount = oldSalesCounts.value(item.id, -1);
        if (oldSalesCount != -1 && oldSalesCount != item.salesCount) {
            emit salesCountUpdated(item.id, item.salesCount);
        }
    }
    
    // 检查是否有新增的菜品
    for (const MenuItem& item : m_menuItems) {
        if (!oldSalesCounts.contains(item.id)) {
            emit salesCountUpdated(item.id, item.salesCount);
        }
    }
}

void MenuManager::checkAndEmitMenuItemChanges(const QHash<QString, MenuItem>& oldMenuItems)
{
    // 检查菜品信息变化并发射相应信号
    for (const MenuItem& item : m_menuItems) {
        if (oldMenuItems.contains(item.id)) {
            const MenuItem& oldItem = oldMenuItems[item.id];
            
            // 检查是否有关键信息发生变化（名称、价格、分类、描述）
            if (oldItem.name != item.name || 
                oldItem.price != item.price || 
                oldItem.category != item.category || 
                oldItem.description != item.description) {
                

                emit menuItemUpdated(item);
            }
        } else {
            // 新增的菜品
            emit menuItemAdded(item);
        }
    }
    
    // 检查是否有菜品被删除
    for (auto it = oldMenuItems.begin(); it != oldMenuItems.end(); ++it) {
        bool found = false;
        for (const MenuItem& item : m_menuItems) {
            if (item.id == it.key()) {
                found = true;
                break;
            }
        }
        if (!found) {
            emit menuItemDeleted(it.key());
        }
    }
}

} // namespace RestaurantSystem
